package emap;

import java.util.ArrayList;

class GridSquare //a GridSquare has an arraylist of Tile objects.
{
	private ArrayList<Tile> myTiles; //This keeps track of all the tiles that exist on a certain square. 
	
	public GridSquare()
	{
		myTiles=new ArrayList<Tile>();
	}
	
	public void addTile(Tile t)
	{
		if(myTiles.size()<2) {
		myTiles.add(t);
		return;
		}
		if(t.getLevel()!=0) myTiles.add(t);
	}
	public void sortThineSelf()
	{
		if(myTiles.size()==0) return;
		//sorts all elements in the arraylist by level
		int minindex=0,minval=myTiles.get(0).getLevel(),maxindex=0,maxval=myTiles.get(0).getLevel(),curindex=0,curval=myTiles.get(0).getLevel();
		int tilelen=myTiles.size();
		int numleft=tilelen,offset=0;
		Tile swaptile=new Tile();
		while(numleft>1)
		{
			for(curindex=offset;curindex<(tilelen-offset);curindex++)
			{
				curval=myTiles.get(curindex).getLevel();
				if(curval<minval){
					minindex=curindex;
					minval=curval;
				}
				if(curval>maxval){
					maxindex=curindex;
					maxval=curval;
				}
			}
			swaptile=myTiles.set(offset,myTiles.get(minindex));
			swaptile=myTiles.set(minindex,swaptile);
			swaptile=myTiles.set(tilelen-offset-1,myTiles.get(maxindex));
			swaptile=myTiles.set(maxindex,swaptile);
			numleft-=2;
			offset++;
		}
		
	}
	public Tile get(int index)
	{
		if (index < myTiles.size() && index>=0)
		{
			return myTiles.get(index);
		}
		else
			return null;
	}
	public int getNumTiles()
	{
		return myTiles.size();
	}
}